<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('基金名称')" prop="fundId">
            <el-select v-model="form.fundId" filterable>
              <el-option
                v-for="item in fundOptions"
                :key="item.fundId"
                :label="item.fundName"
                :value="item.fundId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="margin-top: 15px">
        <!--缴款明细-->
        <div class="area-header">
          <span class="area-header-title">{{ $t('LPA条款') }}</span>
        </div>
        <el-table :data="form.fundInvestorTermsList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('条款类型')" align="center" width="300">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('条款类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'fundInvestorTermsList.' + scope.$index + '.clauseType'"
                :rules="fundInvestorTermsListRules.clauseType"
              >
                <dictSelect
                  v-model="scope.row.clauseType"
                  :clearable="true"
                  dictionary="lpa_type"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('条款内容')" align="center" min-width="220">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('条款内容') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'fundInvestorTermsList.' + scope.$index + '.clauseContent'"
                :rules="fundInvestorTermsListRules.clauseContent"
              >
                <el-input
                  v-model="scope.row.clauseContent"
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 8}"
                  maxlength="2000"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('提醒配置')" align="center" width="100">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" plain @click="remindHandle(scope.$index)">{{ $t('配置') }}</el-button>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="delHandleTerms(scope.$index, scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addFundInvestorTerms">{{ $t("添加") }}</el-button>
        </div>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="fund:investorLpa" />
    </div>
    <!-- 定时提醒 -->
    <el-dialog
      :title="$t('定时提醒')"
      :visible.sync="remindOpen"
      width="40%"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <el-form
        v-if="form.fundInvestorTermsList"
        ref="remindForm"
        :model="form.fundInvestorTermsList[termsIndex]"
        :rules="remindRules"
        label-width="120px"
        label-position="top"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('提醒频率')" prop="reminderFrequency">
              <el-radio-group v-model="form.fundInvestorTermsList[termsIndex].reminderFrequency">
                <el-radio
                  v-for="dict in reminderFrequencyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ $t(dict.dictLabel) }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.fundInvestorTermsList[termsIndex].reminderFrequency === 'TIMER'" :span="12">
            <el-form-item :label="$t('定时提醒时间')" prop="remindTime">
              <el-date-picker
                v-model="form.fundInvestorTermsList[termsIndex].remindTime"
                clearable
                style="width: 200px"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm"
                :placeholder="$t('定时提醒时间')"
              />
            </el-form-item>
          </el-col>
          <el-col v-else :span="24">
            <el-form-item :label="$t('频率提醒表达式')" prop="cron">
              <Cron v-model="form.fundInvestorTermsList[termsIndex].cron" :cron-value.sync="form.fundInvestorTermsList[termsIndex].frequencyCronValue" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒状态')" prop="status">
              <el-switch
                v-model="form.fundInvestorTermsList[termsIndex].status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-text="$t('开启')"
                :inactive-text="$t('关闭')"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒人')" prop="remindUserId">
              <UserSelect
                v-model="form.fundInvestorTermsList[termsIndex].remindUserId"
                :multiple="true"
                :placeholder="$t('提醒人')"
                :popper-append-to-body="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="remindConfirmHandle">{{ $t('确定') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getFundInvestorLpaDto,
  saveFormFundInvestorLpa
} from '@/api/fund/investorLpa/fundInvestorLpa'
    import Cron from '@/components/Cron/index.vue'
    import { delFundInvestorLpa } from '@/api/fund/lpPayment/fundLpPayment'
import { getFundListByCustomerId } from '@/api/fund/investor/fundInvestor'
    export default {
      components: { Cron },
      props: {
        otherBtnHide: {
          type: Boolean,
          default: false
        }
      },
        data() {
            return {
                // 表单参数
                form: {
                  fundInvestorTermsList: []
                },
                // 遮罩层
                loading: false,
                fundInvestorTermsListRules: {
                  clauseType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  clauseContent: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                remindRules: {
                  timerReminderTime: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] },
                  cron: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] },
                  reminderFrequency: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] },
                  remindTime: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] },
                  remindUserId: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                },
                reminderFrequencyOptions: [],
                fundOptions: [],
                remindOpen: false,
                termsIndex: 0,
                operateFlag: 'add',
                // 表单校验
                rules: {
                  fundId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
                }
            }
        },
        created() {
          this.getDicts('reminder_frequency').then(response => {
            this.reminderFrequencyOptions = response.data
          })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                const lpId = this.$route.query.lpId ? this.$route.query.lpId : data.lpId
                if (data != null && data.fundId !== undefined) {
                  getFundInvestorLpaDto(data.fundId, lpId).then(response => {
                    this.form = response.data
                    if (lpId) {
                      getFundListByCustomerId(lpId).then(response => {
                        this.fundOptions = response.data
                      })
                    }
                    this.operateFlag = 'update'
                    this.loading = false
                  }).catch(() => {
                    this.loading = false
                  })
                } else {
                  this.reset()
                  if (lpId) {
                    getFundListByCustomerId(lpId).then(response => {
                      this.fundOptions = response.data
                    })
                  }
                  this.operateFlag = 'add'
                  this.loading = false
                }
            },
            // 配置提醒设置
            remindHandle(index) {
              console.log(this.form.fundInvestorTermsList[index])
              this.termsIndex = index
              this.remindOpen = true
            },
            addFundInvestorTerms() {
              const row = {
                id: undefined,
                clauseType: undefined,
                clauseContent: undefined,
                reminderFrequency: 'TIMER',
                remindTime: undefined,
                cron: undefined,
                status: 1,
                remindUserId: undefined
              }
              if (!(this.form.fundInvestorTermsList instanceof Array)) {
                this.$set(this.form, 'fundInvestorTermsList', [])
              }
              this.$nextTick(() => {
                this.form.fundInvestorTermsList.push(row)
              })
            },
            delHandleTerms(index, row) {
              var that = this
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                  .then(function() {
                    delFundInvestorLpa(id).then(response => {
                      if (response.code === 200) {
                        that.form.fundInvestorTermsList.splice(index, 1)
                        that.msgSuccess(that.$t('删除成功!'))
                      } else {
                        that.msgSuccess(that.$t('删除失败!'))
                      }
                    })
                  }).catch(function() {})
              } else {
                this.form.fundInvestorTermsList.splice(index, 1)
              }
            },
            remindConfirmHandle() {
              this.$refs['remindForm'].validate(valid => {
                if (valid) {
                  this.remindOpen = false
                }
              })
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    clauseType: undefined,
                    clauseContent: undefined,
                    cron: undefined,
                    remindTime: undefined,
                    reminderFrequency: undefined,
                    status: undefined,
                    frequencyCronValue: undefined,
                    remindUserId: undefined,
                    fundInvestorId: undefined,
                    lpId: this.$route.query.lpId,
                    fundId: undefined,
                    createBy: undefined,
                    updateBy: undefined,
                    createTime: undefined,
                    updateTime: undefined,
                    delFlag: undefined,
                    number: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        if (this.form.fundInvestorTermsList && this.form.fundInvestorTermsList.length > 0) {
                          this.loading = true
                          saveFormFundInvestorLpa(this.form).then(response => {
                            if (response.code === 200) {
                              this.msgSuccess(this.$t('保存成功'))
                              this.closeForm()
                            } else {
                              this.msgError(response.msg)
                            }
                            this.loading = false
                          })
                        } else {
                          return this.msgError('请先添加LPA条款列表数据')
                        }
                    } else {
                       this.locationError(document)
                    }
                }).catch(() => {
                    this.loading = false
                })
           }
        }
    }
</script>
